<?php
declare (strict_types=1);

namespace app\command;

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class SyncActivityGoods extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync-activity-goods')
            ->setDescription('同步活动商品');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        Db::table('activity')
            ->field('id,buyin_activity_id')->chunk(100, function ($activity) use ($output) {
                $time = date('Y-m-d H:i:s', time());
                foreach ($activity as $act) {
                    // 待审核 通过 拒绝  0 1 2
                    for ($i = 0; $i <= 2; $i++) {
                        sleep(mt_rand(1,5));
                        $page = 1;
                        $finish = false;
                        $url = "https://buyin.jinritemai.com/api/institution/activity/audit/list";
                        $cookies = config('app.buyin');
                        $client = new Client();
                        $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
                        do {
                            sleep(mt_rand(1,3));
                            $payload = [
                                'audit_status' => $i,
                                'activity_id' => $act['buyin_activity_id'],
                                'page' => $page,
                                'pageSize' => 50,
                                'page_size' => 50,
                            ];
                            try {
                                $response = $client->request('GET', $url, ['query' => $payload, 'timeout' => 5, 'cookies' => $cookieJar]);
                            } catch (\Exception $e) {
                                Log::info('调用接口失败' . $e->getMessage());
                                continue;
                            }
                            $result = json_decode($response->getBody()->getContents(), true);
                            if ($result['code'] == 0) {
                                $goodsList = $result['data'];
                                if ($goodsList) {
                                    foreach ($goodsList as $v) {
                                        $goodsExist = Db::name('activity_goods')->where(['apply_id' => $v['apply_id']])
                                            ->field('id')->find();
                                        $d = $this->getVolume($v['product_name']);
                                        $ginfo = $this->getCategoryId($v['product_id']);
                                        $shop_info = $this->getShop($v['shop_name']);
                                        if ($goodsExist) {
                                            $goods = [
                                                'product_id' => $v['product_id'],
                                                'product_promotion_id' => $v['product_promotion_id'],
                                                'product_name' => $v['product_name'],
                                                'product_price' => $v['product_price'],
                                                'product_img' => $v['product_img'],
                                                'product_stock' => $v['product_stock'],
                                                'shop_name' => $v['shop_name'],
                                                'shop_id' => $v['shop_id'],
                                                'dsr' => $v['dsr'],
                                                'shop_phone' => $v['shop_phone'],
                                                'is_new' => $v['is_new'] ? 1 : 0,
                                                'commission_effect_start_time' => $v['commission_effect_start_time'],
                                                'commission_effect_end_time' => $v['commission_effect_end_time'],
                                                'commission_rate' => $v['commission_rate'],
                                                'common_commission_rate' => $v['common_commission_rate'],
                                                'service_rate' => $v['service_rate'],
                                                'promotion_url' => $v['promotion_url'],
                                                'promotion_price' => $v['promotion_price'],
                                                'promotion_stock' => $v['promotion_stock'],
                                                'gift_info' => $v['gift_info'],
                                                'promotion_step' => $v['promotion_step'],
                                                'audit_status' => $i,
                                                'commission' => round(($v['commission_rate']*$v['promotion_price'])/100, 2),
                                                'volume' => $d ? ($d['day_order_count'] == '-' ? 0 : $d['day_order_count']) : 0,
                                                'order_count' => $d ? ($d['order_count'] == '-' ? 0 : $d['order_count']) : 0,
                                                'pv_count' => $d ? ($d['pv_count'] == '-' ? 0 :$d['pv_count']) : 0,
                                                'hot_promotion_wiseman' => $d ? ($d['total_author_count'] == '-' ? 0 : $d['total_author_count']) :0,
                                                'category_id' => $ginfo['first_cid'],
                                                'detail_delay_desc' => $ginfo['detail_delay_desc'],
                                                'description' => $ginfo['img_list'],
                                                'img_list' => $ginfo['img_list'],
                                                'shop_logo' => $ginfo['shop_logo'],
                                                'shop_tel' => $ginfo['shop_tel'],
                                                'shop_product' => $ginfo['shop_product'],
                                                'shop_service' => $ginfo['shop_service'],
                                                'shop_logistics' => $ginfo['shop_logistics'],
                                                'shop_ids' => $ginfo ? ((isset($ginfo['shop_id']) && $ginfo['shop_id'] != '') ? $ginfo['shop_id'] : '') : '',
                                                'status' => $ginfo ? ((isset($ginfo['product_id']) && $ginfo['product_id'] != '') ? 1 : 0) : 0,
                                                'update_time' => $time
                                            ];
                                            Db::name('activity_goods')->where(['apply_id' => $v['apply_id']])->update($goods);
                                        } else {
                                            $goods = [
                                                'buyin_activity_id' => $act['buyin_activity_id'],
                                                'apply_id' => $v['apply_id'],
                                                'product_id' => $v['product_id'],
                                                'product_promotion_id' => $v['product_promotion_id'],
                                                'product_name' => $v['product_name'],
                                                'product_price' => $v['product_price'],
                                                'product_img' => $v['product_img'],
                                                'product_stock' => $v['product_stock'],
                                                'shop_name' => $v['shop_name'],
                                                'shop_id' => $v['shop_id'],
                                                'dsr' => $v['dsr'],
                                                'shop_phone' => $v['shop_phone'],
                                                'is_new' => $v['is_new'] ? 1 : 0,
                                                'commission_effect_start_time' => $v['commission_effect_start_time'],
                                                'commission_effect_end_time' => $v['commission_effect_end_time'],
                                                'commission_rate' => $v['commission_rate'],
                                                'common_commission_rate' => $v['common_commission_rate'],
                                                'service_rate' => $v['service_rate'],
                                                'promotion_url' => $v['promotion_url'],
                                                'promotion_price' => $v['promotion_price'],
                                                'promotion_stock' => $v['promotion_stock'],
                                                'gift_info' => $v['gift_info'],
                                                'promotion_step' => $v['promotion_step'],
                                                'audit_status' => $i,
                                                'commission' => round(($v['commission_rate']*$v['promotion_price'])/100, 2),
                                                'volume' => $d ? ($d['day_order_count'] == '-' ? 0 : $d['day_order_count']) : 0,
                                                'order_count' => $d ? ($d['order_count'] == '-' ? 0 : $d['order_count']) : 0,
                                                'pv_count' => $d ? ($d['pv_count'] == '-' ? 0 :$d['pv_count']) : 0,
                                                'hot_promotion_wiseman' => $d ? ($d['total_author_count'] == '-' ? 0 : $d['total_author_count']) :0,
                                                'category_id' => $ginfo['first_cid'],
                                                'detail_delay_desc' => $ginfo['detail_delay_desc'],
                                                'description' => $ginfo['img_list'],
                                                'img_list' => $ginfo['img_list'],
                                                'shop_logo' => $ginfo['shop_logo'],
                                                'shop_tel' => $ginfo['shop_tel'],
                                                'shop_product' => $ginfo['shop_product'],
                                                'shop_service' => $ginfo['shop_service'],
                                                'shop_logistics' => $ginfo['shop_logistics'],
                                                'shop_ids' => $ginfo ? ((isset($ginfo['shop_id']) && $ginfo['shop_id'] != '') ? $ginfo['shop_id'] : '') : '',
                                                'status' => $ginfo ? ((isset($ginfo['product_id']) && $ginfo['product_id'] != '') ? 1 : 0) : 0,
                                                'create_time' => $time,
                                                'update_time' => $time
                                            ];
                                            Db::name('activity_goods')->insert($goods);
                                        }
                                    }
                                }
                            } else {
                                Log::info('活动同步失败:' . $result['msg']);
                                $output->writeln('活动同步失败:' . $result['msg']);
                                break;
                            }
                            $totalPage = ceil($result['total'] / 50);
                            $page++;
                            // 当前页数 > 总页数
                            if ($page > $totalPage) {
                                $finish = true;
                            }

                            echo '.';
                        } while (!$finish);
                    }
                }
            });
        // 指令输出
        $output->writeln('同步成功');
    }

    protected function setShop_id(){
        $goods = Db::name('activity_goods')->select();

        if($goods){
            $goods = $goods->toArray();
            foreach($goods as $k=>$v){
                $shop = $this->getShop($v['shop_name']);

                if(isset($shop['shop_id'])){
                    Db::name('activity_goods')->where(['id'=>$v['id']])->update(['shop_ids'=>$shop['shop_id']]);
                }else{
                    Log::info('没有shop_id' . $v['id']);
                    continue;
                }

                echo '.';
                if($k % 100) sleep(3);
            }
        }
    }

    protected function getVolume($product_name){

        $url = 'https://api-service.chanmama.com/v1/product/search';
        $data = '{"keyword":"'.$product_name.'","keyword_type":"","page":1,"price":"","size":50,"filter_coupon":0,"is_aweme_goods":0,"has_live":0,"has_video":0,"tb_max_commission_rate":"","day_pv_count":"","day_order_count":"","big_category":"","first_category":"","second_category":"","platform":"","sort":"auto","order_by":"desc"}';
        $data = json_decode($data, true);
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://www.chanmama.com'
        ];
        $client = new Client();
        try {
            $response = $client->request('post', $url, ['json'=>$data, 'timeout'=>30, 'headers'=>$headers, 'verify' => false]);
            $result = json_decode($response->getBody()->getContents(), true);
            if(isset($result['errCode']) && ($result['errCode'] == 0)){

                if(isset($result['data']['list'][0])){
                    return $result['data']['list'][0];
                }else{
                    return [];
                }
            }else{
                return [];
            }
        }catch (\Exception $e){
            Log::info('调用接口失败' . $e->getMessage());
            exit;
        }

    }

    protected function getShop($shop_name){
        $url = 'https://api-service.chanmama.com/v1/shop/search';
        $data = [
            'page'=>1,
            'big_category'=>'',
            'first_category'=>'',
            'keyword'=>$shop_name,
            'sort'=>'volume',
            'orderby'=>'desc',
            'size'=>50,
            'has_aweme'=>0,
            'has_live'=>0,
            'avg_price'=>'',
            'avg_amount'=>'',
        ];
        $client = new Client();
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => $url
        ];

        try {
            $response = $client->request('GET', $url, ['query'=>$data, 'timeout'=>30, 'headers'=>$headers, 'verify' => false]);
            $result = json_decode($response->getBody()->getContents(), true);
//            echo '<pre>';print_r($result);exit;
            if($result['data']){
                $index = 0;
                if($result['data']['list']){

                    foreach($result['data']['list'] as $k=>$v){
                        if($v['shop_name'] == $shop_name){
                            $index = $k;
                            break;
                        }
                    }

                    return $result['data']['list'][$index];
                }else{
                    return [];
                }
            }else{
                return [];
            }
        }catch (\Exception $e){
            Log::info('调用接口失败' . $e->getMessage());
            exit;
        }
    }

    protected function getCategoryId($productc_id){
        $client = new Client();
        $url = 'https://ec.snssdk.com/product/fxgajaxstaticitem';
        $payload = [
            'b_type_new' => 0,
            'device_id' => 0,
            'id' => $productc_id,
            'preview' => 0
        ];
        $headers = ['user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'];
        try {
            $response = $client->request('GET', $url, ['query' => $payload, 'timeout' => 60, 'headers'=>$headers, 'verify' => false]);
            $result = json_decode($response->getBody()->getContents(), true);
            $data = [
                'first_cid'=>0,
                'detail_delay_desc'=>'',//发货时间
                'description'=>'',//商品描述图片
                'img_list'=>'',//商品轮播图
                'shop_logo'=>'',//商家头像
                'shop_tel'=>'',//商家联系电话
                'shop_product'=>'',//商家体验
                'shop_service'=>'',//商家服务
                'shop_logistics'=>'',//物流体验
                'product_id'=>'',//物流体验
                'shop_id'=>'',
            ];
            if(isset($result['data']) && $result['data']){
                if(isset($result['data']['extra']['category_detail']['first_cid'])){
                    $data['first_cid'] = $result['data']['extra']['category_detail']['first_cid'];
                }

                if(isset($result['data']['detail_delay_desc'])){
                    $data['detail_delay_desc'] = $result['data']['detail_delay_desc'];
                }

                if(isset($result['data']['description'])){
                    $data['description'] = $result['data']['description'];
                }

                if(isset($result['data']['img_list'])){
                    $data['img_list'] = $result['data']['img_list'] ? json_encode($result['data']['img_list']) :'';
                }

                if(isset($result['data']['shop_logo'])){
                    $data['shop_logo'] = $result['data']['shop_logo'];
                }

                if(isset($result['data']['mobile'])){
                    $data['shop_tel'] = $result['data']['mobile'];
                }

                if(isset($result['data']['credit_score'])){
                    $data['shop_product'] = $result['data']['credit_score']['product'];
                    $data['shop_service'] = $result['data']['credit_score']['shop'];
                    $data['shop_logistics'] = $result['data']['credit_score']['logistics'];
                }

                if(isset($result['data']['product_id'])){
                    $data['product_id'] = $result['data']['product_id'];
                }

                if(isset($result['data']['shop_id'])){
                    $data['shop_id'] = $result['data']['shop_id'];
                }

            }

            return $data;
        } catch (\Exception $e) {
            Log::info('调用接口失败' . $e->getMessage());
            exit;
        }
    }
}
